<template>
  <div class="main">
    <!-- 头部输入框 -->
    <el-form :model="queryParams" size="small" :inline="true">
      <el-form-item label="活动名称">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          size="small"
          style="width: 240px"
        ></el-input>
      </el-form-item>

      <el-form-item label="活动类型">
        <el-select
          v-model="queryParams.activityType"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="handleRefresh"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 功能按钮 -->
    <el-row class="btn">
      <el-button
        type="success"
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        >新增</el-button
      >
      <el-button
        type="info"
        icon="el-icon-delete"
        size="mini"
        @click="handleDelete"
        >删除</el-button
      >
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      :row-style="{ height: '180px' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="活动名称"
        width="200"
        prop="activityName"
        align="center"
      >
      </el-table-column>
      <el-table-column label="活动照片" width="200" align="center">
        <template slot-scope="scope">
          <img
            :src="url + scope.row.bucketName + '/' + scope.row.fileName"
            style="height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="activityPlace"
        label="活动地点"
        width="140"
        align="center"
      >
      </el-table-column>

      <el-table-column
        prop="participants"
        label="参会人员"
        width="200"
        align="center"
      >
      </el-table-column>

      <el-table-column prop="activityContent" label="活动内容" align="center">
      </el-table-column>

      <el-table-column label="活动类型" align="center">
        <template slot-scope="scope">
          {{ judgeActive(scope.row.activityType) }}
        </template>
      </el-table-column>

      <el-table-column prop="score" label="活动分值" width="90" align="center">
      </el-table-column>

      <el-table-column label="操作" align="center" width="110">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="80%"
      :before-close="handleClose"
    >
      <!-- 对话框主体部分 -->
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="活动名称"
          prop="activityName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.activityName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="活动时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="dateRange"
            style="width: 480px"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeTime(dateRange)"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="活动图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="upload"
            :before-upload="ImgBeforeAvatarUpload"
            :key="keyVal"
          >
            <img
              v-if="url + form.bucketName + '/' + form.fileName"
              :src="url + form.bucketName + '/' + form.fileName"
              style="width: 100px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item
          label="活动地点"
          prop="activityPlace"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.activityPlace" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="参会人员"
          prop="participants"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.participants" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="活动内容"
          prop="activityContent"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.activityContent"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="活动类型"
          prop="activityType"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.activityType" clearable placeholder="请选择">
            <el-option
              v-for="item in type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="活动分值"
          prop="score"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.score" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!--  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getActivity,
  addActivity,
  updateActivity,
  delActivity,
} from "@/api/activityControl/activity";
import { addFile } from "@/api/uploadFile/file";
import global from "@/global/global.js";

export default {
  data() {
    return {
      // 日期范围
      dateRange: [],
      // 选中数组(存放选中的产品id)
      ids: [],
      // 选中数组(存放选中的产品名称)
      names: [],
      // 使对话框的keyVal值发生变化从而让模板重新编译，使图片即使显示
      keyVal: 0,
      // 对话框的左边距
      formLabelWidth: "120px",
      // 是否显示弹出层
      open: false,
      // 弹出框标题
      title: undefined,
      // 封装图片的ip
      url: global.baseUrl,
      // 存放活动内容
      tableData: [],
      // 活动类型
      type: [
        {
          label: "Sunday学习日",
          value: "0",
        },
        {
          label: "其他",
          value: "1",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        activityName: undefined,
        activityType: undefined,
      },
      // 表格表单
      form: {},
      // 表单校验
      rules: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        activityPlace: [
          { required: true, message: "请输入活动地点", trigger: "blur" },
        ],
        participants: [
          { required: true, message: "请输入参会人员", trigger: "blur" },
        ],
        activityContent: [
          { required: true, message: "请输入活动内容", trigger: "blur" },
        ],
        activityType: [
          { required: true, message: "请选择活动类型", trigger: "change" },
        ],
        score: [{ required: true, message: "请输入活动分值", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      getActivity(this.addDateRange(this.queryParams, this.dateRange)).then(
        (res) => {
          this.tableData = res.rows;
        }
      );
    },
    // 查询表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        activityName: undefined,
        activityType: undefined,
      };
    },
    // 表格表单重置
    resetForm() {
      this.dateRange = [];
      this.form = {
        activityName: undefined,
        activityPlace: undefined,
        participants: undefined,
        activityContent: undefined,
        activityType: undefined,
        score: undefined,
      };
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.names = selection.map((item) => item.activityName);
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    handleRefresh() {
      this.reset();
      this.handleQuery();
    },
    // 修改按钮
    handleUpdate(row) {
      this.resetForm();
      this.dateRange.push(row.startTime);
      this.dateRange.push(row.endTime);
      this.open = true;
      this.form = row;
      this.title = "修改活动信息";
    },
    // 删除按钮
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      const roleNames = row.activityName || this.names;
      this.$modal
        .confirm('是否确认删除活动名称为"' + roleNames + '"的数据项？')
        .then(function () {
          return delActivity(roleIds);
        })
        .then(() => {
          this.getList();
        });
    },
    // 新增按钮
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加活动信息";
    },
    // 判断活动类型
    judgeActive(value) {
      for (let i = 0; i < this.type.length; i++) {
        if (value == this.type[i].value) {
          return this.type[i].label;
        }
      }
    },
    // 上传图片时接收到file对象并调用添加图片的接口
    upload(f) {
      // 1. 获取表单数据   formData 表单数据
      let formData = new FormData();
      formData.append("file", f.file);
      // 2. 发起请求
      addFile(formData).then((res) => {
        // 3. 请求成功之后  图片回显
        this.form.imgId = res.data.imgId;
        this.form.bucketName = res.data.bucketName;
        this.form.fileName = res.data.fileName;
        // 将对话框中的key的值+1，使模板重新编译从而使图片显示出来
        this.keyVal++;
      });
    },
    //上传前校验图片规则
    ImgBeforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 和 Png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },
    // 关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.getList();
          done();
        })
        .catch((_) => {});
    },
    // 取消对话框
    cancel() {
      this.getList();
      this.open = false;
    },
    /* 提交(确定)按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateActivity(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            addActivity(this.form).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.open = false;
            });
          }
        }
      });
    },
    // 对话框选择时间
    changeTime(time) {
      this.form.startTime = time[0];
      this.form.endTime = time[1];
    },
  },
};
</script>

<style scoped>
.main {
  margin: 20px;
}
</style>